import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

//获取应用实例
const app = getApp();
Page({
    data: {
        fileList: [],
        canIUse: qq.canIUse('button.open-type.getUserInfo'),
        show: true,
        username: "",
        windowSwitch: false,
        antistop: "",
        loading: false,
        userGroup: "",
        affirm: ""
    },
    async onShow() {
        const db = qq.cloud.database()
        const command = db.command;
        const This = this;
        db.collection(app.data.whoNumber)
            .where({
                unionId: command.eq(app.data.unionId)
            })
            .get()
            .then(res => {
                if (res.data.length != 0) {
                    app.data.userName = res.data[0].Name;
                }
            }).catch(err => {});
        await db.collection("act")
            .where({
                alliance: app.data.alliance
            })
            .get()
            .then(res => {
                app.data.act = res.data[0].act.pop();
                This.setData({ antistop: res.data[0].antistop.pop() });
                app.data.actTimestamp = res.data[0].timestamp.pop();
            }).catch(err => {
                console.log(err);
            });
        await db.collection(app.data.whoSign).where({
                unionId: app.data.unionId
            })
            .get()
            .then(res => {
                try {
                    if (res.data[0].group) {
                        this.setData({ userGroup: res.data[0].group });
                    }
                    if (res.data[0][app.data.act] == '√') {
                        this.setData({ affirm: "√" });
                    } else {
                        this.setData({ affirm: "x" });
                    }
                } catch (err) {

                }
            });
    },
    onShareAppMessage() {
        qq.showShareMenu({
            showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
        });
    },
    afterRead(event) {
        const { file } = event.detail;
        const { fileList = [] } = this.data;
        fileList.push({ url: file.url });
        this.setData({ fileList });
    },
    deleteIcon() {
        const { fileList = [] } = this.data;
        fileList.shift();
        this.setData({ fileList });
    },
    load() {
        let This = this;
        Dialog.confirm({
                title: '提示',
                message: '图片仅作考核签到用途',
            })
            .then(() => {
                if (this.data.affirm == '√') {
                    Toast('已参与本次行动，请勿重复上传');
                    const { fileList = [] } = This.data;
                    fileList.shift();
                    This.setData({ fileList });
                    return;
                }
                This.setData({ loading: true });
                this.loadFile();
            })
            .catch(() => {
                // on cancel
            });
    },
    async loadFile() {
        let fileID = "";
        let act = '';
        let This = this;
        const db = qq.cloud.database()
        const _ = db.command;
        if (this.data.fileList.length == 0) {
            this.isNull();
            This.setData({ loading: false });
            return;
        }
        if (this.data.fileList.length != 0) {
            var filePath = app.data.userName;
            var fileName = `${filePath}/${app.data.act}.jpg`;
            qq.cloud.uploadFile({
                    cloudPath: fileName,
                    filePath: this.data.fileList[0].url // 文件路径
                })
                .then(res => {
                    fileID = res.fileID;
                    this.loadFileUrl(fileID);
                })
                .catch(error => {});
        }
    },
    isNull() {
        Dialog.alert({
            title: '错误',
            message: '请确认是否放入图片',
        }).then(() => {

        });
    },
    async loadFileUrl(fileID) {
        let This = this;
        await qq.cloud.getTempFileURL({
                fileList: [{
                    fileID: fileID,
                    maxAge: 60 * 60 // one hour
                }]
            })
            .then(res => {
                This.characterRecognition(res.fileList[0].download_url);
            })
            .catch(error => {});
    },
    async characterRecognition(fileList) {
        let token = "";
        let This = this;
        let numb = 0;
        const db = qq.cloud.database()
        const _ = db.command;
        await qq.request({
            url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=abpnYN66njXvYjyHTh49DWSz&client_secret=iSEPyPAYyrVg37anyDDwU61kDwvuIHMB',
            method: "POST",
            "content-type": "application/x-www-form-urlencoded",
            success(res) {
                token = res.data.access_token;
                userGroup = This.data.userGroup;

                qq.request({
                    url: `https://aip.baidubce.com/rest/2.0/ocr/v1/webimage?access_token=${token}`,
                    method: "POST",
                    "content-type": "application/x-www-form-urlencoded",
                    data: `url=${fileList}`,
                    success(res) {
                        if (res == null) {
                            Toast("图片识别到错误");
                            const { fileList = [] } = This.data;
                            fileList.shift();
                            This.setData({ fileList, loading: false });
                        }
                        if (userGroup == "") {
                            userGroup = "未分组"
                        }
                        dataList = This.data.antistop[userGroup].slice();
                        let username = app.data.userName;
                        dataList.push(username);
                        // console.log(dataList);
                        // console.log(res.data.words_result);
                        for (let i of res.data.words_result) {
                            let myStr = i.words.replace(" ", "");
                            try {
                                for (let j in dataList) {
                                    let key = new RegExp(dataList[j], "ig");
                                    if (key.test(myStr)) {
                                        numb++;
                                        // console.log(myStr);
                                        dataList.splice(j, 1);
                                    }
                                }
                            } catch (err) {
                                Toast('该分组未设置任务');
                                return;
                            }
                        }
                        if (numb >= 2) {
                            This.loadSuccess();
                        } else {
                            db.collection(app.data.whoSign)
                                .where({
                                    unionId: _.eq(app.data.unionId),
                                    alliance: app.data.alliance
                                })
                                .update({
                                    data: {
                                        [app.data.act]: _.set("待定")
                                    }
                                })
                                .then(res => {
                                    db.collection(app.data.whoSign)
                                        .where({
                                            unionId: _.eq(app.data.unionId)
                                        })
                                        .get()
                                        .then(res => {
                                            if (res.data.length == 0) {
                                                db.collection(app.data.whoSign).add({
                                                        data: {
                                                            userName: app.data.userName,
                                                            unionId: app.data.unionId,
                                                            alliance: app.data.alliance
                                                        },
                                                    }).then(() => {})
                                                    .catch(() => {})
                                            }
                                        }).catch(() => {})
                                    Toast("识别错误。将进入人工审核");
                                    const { fileList = [] } = This.data;
                                    fileList.shift();
                                    This.setData({ fileList, loading: false });
                                }).catch(err => {
                                    console.log(err);
                                    const { fileList = [] } = This.data;
                                    fileList.shift();
                                    This.setData({ fileList, loading: false });
                                });
                        }
                    },
                    fail(err) {
                        This.setData({ loading: false });
                        Toast("照片上传失败");
                    },
                    complete() {
                        This.setData({ loading: false });
                    }
                })
            },
            fail(err) {
                This.setData({ loading: false });
                Toast("照片上传失败");
            }
        })
    },
    async loadSuccess() {
        const db = qq.cloud.database()
        const _ = db.command;
        let This = this;
        await db.collection(app.data.whoSign)
            .where({
                unionId: _.eq(app.data.unionId)
            })
            .get()
            .then(res => {
                let onHook = "";
                try {
                    if (res.data[0][app.data.act] == '挂机') {
                        onHook = res.data[0][app.data.act];
                    }
                } catch (err) {}
                if (res.data.length == 0) {
                    db.collection(app.data.whoSign).add({
                            data: {
                                userName: app.data.userName,
                                unionId: app.data.unionId,
                                alliance: app.data.alliance
                            },
                        })
                        .then(res => {
                            db.collection(app.data.whoSign)
                                .where({
                                    unionId: _.eq(app.data.unionId),
                                })
                                .update({
                                    data: {
                                        [app.data.act]: _.set("√")
                                    }
                                })
                                .then(res => {
                                    This.setData({ loading: false });
                                    Toast("照片上传完成");
                                    const { fileList = [] } = This.data;
                                    fileList.shift();
                                    This.setData({ fileList, affirm: "√" });
                                }).catch(err => {});
                        })
                        .catch(err => {});
                } else {
                    db.collection(app.data.whoSign)
                        .where({
                            unionId: _.eq(app.data.unionId),
                            [app.data.act]: _.neq('挂机')
                        })
                        .update({
                            data: {
                                [app.data.act]: _.set("√"),

                            }
                        })
                        .then(res => {
                            if (onHook) {
                                Toast('已被判定挂机');
                            } else {
                                Toast("照片上传完成");
                            }
                            const { fileList = [] } = This.data;
                            fileList.shift();
                            This.setData({ fileList, loading: false });
                        }).catch(err => {});
                }
            });
    }
})